package com.stu.reflection;

import java.lang.annotation.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Java反射机制演示
 * 
 * 本类演示了Java反射的核心概念，包括：
 * 1. 反射的基本概念和原理
 * 2. Class对象的获取方式
 * 3. 构造器反射（Constructor）
 * 4. 字段反射（Field）
 * 5. 方法反射（Method）
 * 6. 注解反射（Annotation）
 * 7. 泛型反射（Generic）
 * 8. 动态代理（Proxy）
 * 9. 反射的性能优化
 * 10. 反射的安全性考虑
 * 
 * @author 学习者
 * @version 1.0
 * @since JDK 1.8
 */
public class ReflectionDemo {
    
    /**
     * 主方法：演示反射的各个方面
     */
    public static void main(String[] args) {
        System.out.println("=== Java反射机制演示 ===");
        
        try {
            // 1. 演示反射基础
            demonstrateReflectionBasics();
            
            // 2. 演示Class对象
            demonstrateClassObject();
            
            // 3. 演示构造器反射
            demonstrateConstructorReflection();
            
            // 4. 演示字段反射
            demonstrateFieldReflection();
            
            // 5. 演示方法反射
            demonstrateMethodReflection();
            
            // 6. 演示注解反射
            demonstrateAnnotationReflection();
            
            // 7. 演示泛型反射
            demonstrateGenericReflection();
            
            // 8. 演示动态代理
            demonstrateDynamicProxy();
            
            // 9. 演示反射性能
            demonstrateReflectionPerformance();
            
            // 10. 演示反射应用场景
            demonstrateReflectionApplications();
            
        } catch (Exception e) {
            System.err.println("演示过程中发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 演示反射基础
     */
    private static void demonstrateReflectionBasics() {
        System.out.println("\n=== 反射基础演示 ===");
        
        System.out.println("反射的定义：");
        System.out.println("反射是Java程序在运行时检查和修改自身结构和行为的能力。");
        
        System.out.println("\n反射的核心类：");
        System.out.println("1. Class：表示类的信息");
        System.out.println("2. Constructor：表示构造器信息");
        System.out.println("3. Field：表示字段信息");
        System.out.println("4. Method：表示方法信息");
        System.out.println("5. Annotation：表示注解信息");
        
        System.out.println("\n反射的应用场景：");
        System.out.println("1. 框架开发：Spring、Hibernate等");
        System.out.println("2. 序列化/反序列化");
        System.out.println("3. 动态代理");
        System.out.println("4. 注解处理");
        System.out.println("5. 单元测试");
        System.out.println("6. IDE工具");
        
        System.out.println("\n反射的优缺点：");
        System.out.println("优点：");
        System.out.println("- 灵活性：运行时动态操作");
        System.out.println("- 通用性：编写通用代码");
        System.out.println("- 扩展性：支持插件化架构");
        
        System.out.println("缺点：");
        System.out.println("- 性能开销：比直接调用慢");
        System.out.println("- 安全限制：可能破坏封装性");
        System.out.println("- 代码复杂：难以理解和维护");
    }
    
    /**
     * 演示Class对象
     */
    private static void demonstrateClassObject() throws ClassNotFoundException {
        System.out.println("\n=== Class对象演示 ===");
        
        System.out.println("Class对象：Java反射的入口点");
        
        // 1. 获取Class对象的三种方式
        System.out.println("\n1. 获取Class对象的方式：");
        
        // 方式1：通过类名.class
        Class<String> clazz1 = String.class;
        System.out.println("方式1 - 类名.class：" + clazz1.getName());
        
        // 方式2：通过对象.getClass()
        String str = "Hello";
        Class<?> clazz2 = str.getClass();
        System.out.println("方式2 - 对象.getClass()：" + clazz2.getName());
        
        // 方式3：通过Class.forName()
        Class<?> clazz3 = Class.forName("java.lang.String");
        System.out.println("方式3 - Class.forName()：" + clazz3.getName());
        
        // 验证是否为同一个Class对象
        System.out.println("\n三种方式获取的是同一个Class对象：" + (clazz1 == clazz2 && clazz2 == clazz3));
        
        // 2. Class对象的基本信息
        System.out.println("\n2. Class对象的基本信息：");
        demonstrateClassInfo(Student.class);
        
        // 3. Class对象的层次结构
        System.out.println("\n3. Class对象的层次结构：");
        demonstrateClassHierarchy(Student.class);
    }
    
    /**
     * 演示Class信息
     */
    private static void demonstrateClassInfo(Class<?> clazz) {
        System.out.println("类信息分析：" + clazz.getName());
        
        // 基本信息
        System.out.println("- 简单名称：" + clazz.getSimpleName());
        System.out.println("- 规范名称：" + clazz.getCanonicalName());
        System.out.println("- 包名：" + clazz.getPackage().getName());
        System.out.println("- 修饰符：" + Modifier.toString(clazz.getModifiers()));
        
        // 类型判断
        System.out.println("- 是否为接口：" + clazz.isInterface());
        System.out.println("- 是否为抽象类：" + Modifier.isAbstract(clazz.getModifiers()));
        System.out.println("- 是否为枚举：" + clazz.isEnum());
        System.out.println("- 是否为注解：" + clazz.isAnnotation());
        System.out.println("- 是否为数组：" + clazz.isArray());
        System.out.println("- 是否为原始类型：" + clazz.isPrimitive());
    }
    
    /**
     * 演示Class层次结构
     */
    private static void demonstrateClassHierarchy(Class<?> clazz) {
        System.out.println("类层次结构分析：" + clazz.getName());
        
        // 父类
        Class<?> superClass = clazz.getSuperclass();
        if (superClass != null) {
            System.out.println("- 父类：" + superClass.getName());
        }
        
        // 接口
        Class<?>[] interfaces = clazz.getInterfaces();
        if (interfaces.length > 0) {
            System.out.println("- 实现的接口：");
            for (Class<?> intf : interfaces) {
                System.out.println("  * " + intf.getName());
            }
        }
        
        // 内部类
        Class<?>[] innerClasses = clazz.getDeclaredClasses();
        if (innerClasses.length > 0) {
            System.out.println("- 内部类：");
            for (Class<?> inner : innerClasses) {
                System.out.println("  * " + inner.getSimpleName());
            }
        }
        
        // 外部类
        Class<?> enclosingClass = clazz.getEnclosingClass();
        if (enclosingClass != null) {
            System.out.println("- 外部类：" + enclosingClass.getName());
        }
    }
    
    /**
     * 演示构造器反射
     */
    private static void demonstrateConstructorReflection() throws Exception {
        System.out.println("\n=== 构造器反射演示 ===");
        
        System.out.println("构造器反射：动态创建对象实例");
        
        Class<Student> clazz = Student.class;
        
        // 1. 获取所有构造器
        System.out.println("\n1. 获取所有构造器：");
        Constructor<?>[] constructors = clazz.getDeclaredConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println("- " + constructor);
            System.out.println("  参数类型：" + Arrays.toString(constructor.getParameterTypes()));
            System.out.println("  修饰符：" + Modifier.toString(constructor.getModifiers()));
        }
        
        // 2. 获取特定构造器并创建对象
        System.out.println("\n2. 使用构造器创建对象：");
        
        // 无参构造器
        Constructor<Student> defaultConstructor = clazz.getDeclaredConstructor();
        Student student1 = defaultConstructor.newInstance();
        System.out.println("无参构造器创建：" + student1);
        
        // 有参构造器
        Constructor<Student> paramConstructor = clazz.getDeclaredConstructor(String.class, int.class, String.class);
        Student student2 = paramConstructor.newInstance("张三", 20, "计算机科学");
        System.out.println("有参构造器创建：" + student2);
        
        // 私有构造器
        System.out.println("\n3. 访问私有构造器：");
        Constructor<Student> privateConstructor = clazz.getDeclaredConstructor(String.class);
        privateConstructor.setAccessible(true); // 设置可访问
        Student student3 = privateConstructor.newInstance("李四");
        System.out.println("私有构造器创建：" + student3);
        
        System.out.println("\n构造器反射要点：");
        System.out.println("1. getDeclaredConstructors()：获取所有构造器");
        System.out.println("2. getConstructors()：获取公共构造器");
        System.out.println("3. getDeclaredConstructor(Class...)：获取特定构造器");
        System.out.println("4. setAccessible(true)：访问私有构造器");
        System.out.println("5. newInstance(Object...)：创建对象实例");
    }
    
    /**
     * 演示字段反射
     */
    private static void demonstrateFieldReflection() throws Exception {
        System.out.println("\n=== 字段反射演示 ===");
        
        System.out.println("字段反射：动态访问和修改对象字段");
        
        Student student = new Student("王五", 22, "软件工程");
        Class<Student> clazz = Student.class;
        
        // 1. 获取所有字段
        System.out.println("\n1. 获取所有字段：");
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            System.out.println("- " + field.getName() + " : " + field.getType().getSimpleName());
            System.out.println("  修饰符：" + Modifier.toString(field.getModifiers()));
            
            // 获取字段注解
            Annotation[] annotations = field.getAnnotations();
            if (annotations.length > 0) {
                System.out.println("  注解：" + Arrays.toString(annotations));
            }
        }
        
        // 2. 读取字段值
        System.out.println("\n2. 读取字段值：");
        
        // 公共字段
        Field nameField = clazz.getDeclaredField("name");
        Object nameValue = nameField.get(student);
        System.out.println("name字段值：" + nameValue);
        
        // 私有字段
        Field ageField = clazz.getDeclaredField("age");
        ageField.setAccessible(true); // 设置可访问
        Object ageValue = ageField.get(student);
        System.out.println("age字段值：" + ageValue);
        
        // 静态字段
        Field countField = clazz.getDeclaredField("count");
        countField.setAccessible(true);
        Object countValue = countField.get(null); // 静态字段传null
        System.out.println("count字段值：" + countValue);
        
        // 3. 修改字段值
        System.out.println("\n3. 修改字段值：");
        System.out.println("修改前：" + student);
        
        // 修改name字段
        nameField.set(student, "赵六");
        
        // 修改age字段
        ageField.set(student, 25);
        
        // 修改final字段（需要特殊处理）
        Field majorField = clazz.getDeclaredField("major");
        majorField.setAccessible(true);
        
        // 移除final修饰符
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(majorField, majorField.getModifiers() & ~Modifier.FINAL);
        
        majorField.set(student, "数据科学");
        
        System.out.println("修改后：" + student);
        
        // 4. 字段类型分析
        System.out.println("\n4. 字段类型分析：");
        demonstrateFieldTypes(clazz);
        
        System.out.println("\n字段反射要点：");
        System.out.println("1. getDeclaredFields()：获取所有字段");
        System.out.println("2. getFields()：获取公共字段");
        System.out.println("3. getDeclaredField(String)：获取特定字段");
        System.out.println("4. setAccessible(true)：访问私有字段");
        System.out.println("5. get(Object)/set(Object, Object)：读写字段值");
        System.out.println("6. 静态字段操作时对象参数传null");
    }
    
    /**
     * 演示字段类型分析
     */
    private static void demonstrateFieldTypes(Class<?> clazz) throws Exception {
        Field[] fields = clazz.getDeclaredFields();
        
        for (Field field : fields) {
            System.out.println("字段：" + field.getName());
            
            // 基本类型信息
            Class<?> type = field.getType();
            System.out.println("  类型：" + type.getName());
            System.out.println("  是否为原始类型：" + type.isPrimitive());
            
            // 泛型类型信息
            Type genericType = field.getGenericType();
            if (genericType instanceof ParameterizedType) {
                ParameterizedType paramType = (ParameterizedType) genericType;
                System.out.println("  泛型类型：" + paramType);
                System.out.println("  原始类型：" + paramType.getRawType());
                System.out.println("  类型参数：" + Arrays.toString(paramType.getActualTypeArguments()));
            }
            
            System.out.println();
        }
    }
    
    /**
     * 演示方法反射
     */
    private static void demonstrateMethodReflection() throws Exception {
        System.out.println("\n=== 方法反射演示 ===");
        
        System.out.println("方法反射：动态调用对象方法");
        
        Student student = new Student("孙七", 21, "人工智能");
        Class<Student> clazz = Student.class;
        
        // 1. 获取所有方法
        System.out.println("\n1. 获取所有方法：");
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println("- " + method.getName());
            System.out.println("  返回类型：" + method.getReturnType().getSimpleName());
            System.out.println("  参数类型：" + Arrays.toString(method.getParameterTypes()));
            System.out.println("  修饰符：" + Modifier.toString(method.getModifiers()));
            
            // 获取方法注解
            Annotation[] annotations = method.getAnnotations();
            if (annotations.length > 0) {
                System.out.println("  注解：" + Arrays.toString(annotations));
            }
            System.out.println();
        }
        
        // 2. 调用无参方法
        System.out.println("\n2. 调用无参方法：");
        Method toStringMethod = clazz.getMethod("toString");
        Object result1 = toStringMethod.invoke(student);
        System.out.println("toString()结果：" + result1);
        
        Method getNameMethod = clazz.getMethod("getName");
        Object result2 = getNameMethod.invoke(student);
        System.out.println("getName()结果：" + result2);
        
        // 3. 调用有参方法
        System.out.println("\n3. 调用有参方法：");
        Method setNameMethod = clazz.getMethod("setName", String.class);
        setNameMethod.invoke(student, "周八");
        System.out.println("setName()后：" + student.getName());
        
        Method studyMethod = clazz.getMethod("study", String.class);
        Object result3 = studyMethod.invoke(student, "Java反射");
        System.out.println("study()结果：" + result3);
        
        // 4. 调用私有方法
        System.out.println("\n4. 调用私有方法：");
        Method privateMethod = clazz.getDeclaredMethod("calculateGPA", double[].class);
        privateMethod.setAccessible(true);
        double[] scores = {85.5, 92.0, 78.5, 88.0};
        Object result4 = privateMethod.invoke(student, (Object) scores);
        System.out.println("calculateGPA()结果：" + result4);
        
        // 5. 调用静态方法
        System.out.println("\n5. 调用静态方法：");
        Method staticMethod = clazz.getDeclaredMethod("getNextId");
        staticMethod.setAccessible(true);
        Object result5 = staticMethod.invoke(null); // 静态方法传null
        System.out.println("getNextId()结果：" + result5);
        
        // 6. 方法参数分析
        System.out.println("\n6. 方法参数分析：");
        demonstrateMethodParameters(studyMethod);
        
        System.out.println("\n方法反射要点：");
        System.out.println("1. getDeclaredMethods()：获取所有方法");
        System.out.println("2. getMethods()：获取公共方法");
        System.out.println("3. getDeclaredMethod(String, Class...)：获取特定方法");
        System.out.println("4. setAccessible(true)：访问私有方法");
        System.out.println("5. invoke(Object, Object...)：调用方法");
        System.out.println("6. 静态方法调用时对象参数传null");
    }
    
    /**
     * 演示方法参数分析
     */
    private static void demonstrateMethodParameters(Method method) {
        System.out.println("方法参数分析：" + method.getName());
        
        // 参数类型
        Class<?>[] paramTypes = method.getParameterTypes();
        System.out.println("参数类型：" + Arrays.toString(paramTypes));
        
        // 参数个数
        System.out.println("参数个数：" + method.getParameterCount());
        
        // 参数信息（JDK 8+）
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            Parameter param = parameters[i];
            System.out.println("参数" + i + "：");
            System.out.println("  名称：" + param.getName());
            System.out.println("  类型：" + param.getType());
            System.out.println("  修饰符：" + Modifier.toString(param.getModifiers()));
        }
        
        // 泛型参数
        Type[] genericParamTypes = method.getGenericParameterTypes();
        if (genericParamTypes.length > 0) {
            System.out.println("泛型参数类型：" + Arrays.toString(genericParamTypes));
        }
        
        // 返回类型
        System.out.println("返回类型：" + method.getReturnType());
        System.out.println("泛型返回类型：" + method.getGenericReturnType());
        
        // 异常类型
        Class<?>[] exceptionTypes = method.getExceptionTypes();
        if (exceptionTypes.length > 0) {
            System.out.println("异常类型：" + Arrays.toString(exceptionTypes));
        }
    }
    
    /**
     * 演示注解反射
     */
    private static void demonstrateAnnotationReflection() throws Exception {
        System.out.println("\n=== 注解反射演示 ===");
        
        System.out.println("注解反射：运行时处理注解信息");
        
        Class<Student> clazz = Student.class;
        
        // 1. 类级别注解
        System.out.println("\n1. 类级别注解：");
        if (clazz.isAnnotationPresent(Entity.class)) {
            Entity entity = clazz.getAnnotation(Entity.class);
            System.out.println("@Entity注解：");
            System.out.println("  表名：" + entity.tableName());
            System.out.println("  描述：" + entity.description());
        }
        
        // 2. 字段级别注解
        System.out.println("\n2. 字段级别注解：");
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Column.class)) {
                Column column = field.getAnnotation(Column.class);
                System.out.println("字段 " + field.getName() + " 的@Column注解：");
                System.out.println("  列名：" + column.name());
                System.out.println("  是否可空：" + column.nullable());
                System.out.println("  长度：" + column.length());
            }
            
            if (field.isAnnotationPresent(Deprecated.class)) {
                System.out.println("字段 " + field.getName() + " 已过时");
            }
        }
        
        // 3. 方法级别注解
        System.out.println("\n3. 方法级别注解：");
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(Transactional.class)) {
                Transactional tx = method.getAnnotation(Transactional.class);
                System.out.println("方法 " + method.getName() + " 的@Transactional注解：");
                System.out.println("  事务类型：" + tx.value());
                System.out.println("  只读：" + tx.readOnly());
            }
        }
        
        // 4. 注解处理器示例
        System.out.println("\n4. 注解处理器示例：");
        processEntityAnnotations(clazz);
        
        System.out.println("\n注解反射要点：");
        System.out.println("1. isAnnotationPresent(Class)：检查注解是否存在");
        System.out.println("2. getAnnotation(Class)：获取特定注解");
        System.out.println("3. getAnnotations()：获取所有注解");
        System.out.println("4. getDeclaredAnnotations()：获取直接声明的注解");
        System.out.println("5. 注解必须是@Retention(RetentionPolicy.RUNTIME)");
    }
    
    /**
     * 处理实体注解
     */
    private static void processEntityAnnotations(Class<?> clazz) {
        System.out.println("实体注解处理器：");
        
        if (!clazz.isAnnotationPresent(Entity.class)) {
            System.out.println("类 " + clazz.getName() + " 不是实体类");
            return;
        }
        
        Entity entity = clazz.getAnnotation(Entity.class);
        System.out.println("处理实体：" + entity.tableName());
        
        // 生成SQL建表语句
        StringBuilder sql = new StringBuilder();
        sql.append("CREATE TABLE ").append(entity.tableName()).append(" (\n");
        
        Field[] fields = clazz.getDeclaredFields();
        List<String> columns = new ArrayList<>();
        
        for (Field field : fields) {
            if (field.isAnnotationPresent(Column.class)) {
                Column column = field.getAnnotation(Column.class);
                StringBuilder columnDef = new StringBuilder();
                columnDef.append("  ").append(column.name());
                
                // 根据Java类型推断SQL类型
                Class<?> fieldType = field.getType();
                if (fieldType == String.class) {
                    columnDef.append(" VARCHAR(").append(column.length()).append(")");
                } else if (fieldType == int.class || fieldType == Integer.class) {
                    columnDef.append(" INT");
                } else if (fieldType == long.class || fieldType == Long.class) {
                    columnDef.append(" BIGINT");
                } else if (fieldType == double.class || fieldType == Double.class) {
                    columnDef.append(" DOUBLE");
                }
                
                if (!column.nullable()) {
                    columnDef.append(" NOT NULL");
                }
                
                columns.add(columnDef.toString());
            }
        }
        
        sql.append(String.join(",\n", columns));
        sql.append("\n);");
        
        System.out.println("生成的SQL：");
        System.out.println(sql.toString());
    }
    
    /**
     * 演示泛型反射
     */
    private static void demonstrateGenericReflection() throws Exception {
        System.out.println("\n=== 泛型反射演示 ===");
        
        System.out.println("泛型反射：运行时获取泛型信息");
        
        // 1. 类级别泛型
        System.out.println("\n1. 类级别泛型：");
        Class<GenericClass> clazz = GenericClass.class;
        TypeVariable<?>[] typeParams = clazz.getTypeParameters();
        for (TypeVariable<?> typeParam : typeParams) {
            System.out.println("类型参数：" + typeParam.getName());
            System.out.println("边界：" + Arrays.toString(typeParam.getBounds()));
        }
        
        // 2. 字段泛型
        System.out.println("\n2. 字段泛型：");
        Field listField = clazz.getDeclaredField("list");
        Type genericType = listField.getGenericType();
        if (genericType instanceof ParameterizedType) {
            ParameterizedType paramType = (ParameterizedType) genericType;
            System.out.println("字段 list 的泛型信息：");
            System.out.println("  原始类型：" + paramType.getRawType());
            System.out.println("  类型参数：" + Arrays.toString(paramType.getActualTypeArguments()));
        }
        
        Field mapField = clazz.getDeclaredField("map");
        Type mapGenericType = mapField.getGenericType();
        if (mapGenericType instanceof ParameterizedType) {
            ParameterizedType paramType = (ParameterizedType) mapGenericType;
            System.out.println("字段 map 的泛型信息：");
            System.out.println("  原始类型：" + paramType.getRawType());
            System.out.println("  类型参数：" + Arrays.toString(paramType.getActualTypeArguments()));
        }
        
        // 3. 方法泛型
        System.out.println("\n3. 方法泛型：");
        Method genericMethod = clazz.getDeclaredMethod("process", Object.class);
        
        // 方法类型参数
        TypeVariable<?>[] methodTypeParams = genericMethod.getTypeParameters();
        for (TypeVariable<?> typeParam : methodTypeParams) {
            System.out.println("方法类型参数：" + typeParam.getName());
            System.out.println("边界：" + Arrays.toString(typeParam.getBounds()));
        }
        
        // 方法参数泛型
        Type[] paramTypes = genericMethod.getGenericParameterTypes();
        System.out.println("方法参数泛型：" + Arrays.toString(paramTypes));
        
        // 方法返回类型泛型
        Type returnType = genericMethod.getGenericReturnType();
        System.out.println("方法返回类型泛型：" + returnType);
        
        // 4. 继承关系中的泛型
        System.out.println("\n4. 继承关系中的泛型：");
        demonstrateInheritanceGenerics();
        
        System.out.println("\n泛型反射要点：");
        System.out.println("1. getGenericType()：获取字段的泛型类型");
        System.out.println("2. getGenericParameterTypes()：获取方法参数的泛型类型");
        System.out.println("3. getGenericReturnType()：获取方法返回类型的泛型");
        System.out.println("4. ParameterizedType：参数化类型");
        System.out.println("5. TypeVariable：类型变量");
        System.out.println("6. 泛型擦除：运行时部分泛型信息丢失");
    }
    
    /**
     * 演示继承关系中的泛型
     */
    private static void demonstrateInheritanceGenerics() {
        Class<StringList> clazz = StringList.class;
        
        // 获取父类的泛型信息
        Type superType = clazz.getGenericSuperclass();
        if (superType instanceof ParameterizedType) {
            ParameterizedType paramType = (ParameterizedType) superType;
            System.out.println("父类泛型信息：");
            System.out.println("  原始类型：" + paramType.getRawType());
            System.out.println("  类型参数：" + Arrays.toString(paramType.getActualTypeArguments()));
        }
        
        // 获取接口的泛型信息
        Type[] interfaces = clazz.getGenericInterfaces();
        for (Type intf : interfaces) {
            if (intf instanceof ParameterizedType) {
                ParameterizedType paramType = (ParameterizedType) intf;
                System.out.println("接口泛型信息：");
                System.out.println("  原始类型：" + paramType.getRawType());
                System.out.println("  类型参数：" + Arrays.toString(paramType.getActualTypeArguments()));
            }
        }
    }
    
    /**
     * 演示动态代理
     */
    private static void demonstrateDynamicProxy() {
        System.out.println("\n=== 动态代理演示 ===");
        
        System.out.println("动态代理：运行时创建代理对象");
        
        // 1. JDK动态代理
        System.out.println("\n1. JDK动态代理：");
        demonstrateJDKProxy();
        
        // 2. 代理模式应用
        System.out.println("\n2. 代理模式应用：");
        demonstrateProxyApplications();
        
        System.out.println("\n动态代理要点：");
        System.out.println("1. JDK动态代理：基于接口，使用Proxy类");
        System.out.println("2. CGLIB代理：基于继承，可代理类");
        System.out.println("3. InvocationHandler：调用处理器");
        System.out.println("4. 应用场景：AOP、事务管理、日志记录等");
    }
    
    /**
     * 演示JDK动态代理
     */
    private static void demonstrateJDKProxy() {
        // 创建目标对象
        UserService userService = new UserServiceImpl();
        
        // 创建代理对象
        UserService proxy = (UserService) Proxy.newProxyInstance(
            userService.getClass().getClassLoader(),
            userService.getClass().getInterfaces(),
            new ServiceInvocationHandler(userService)
        );
        
        System.out.println("代理对象类型：" + proxy.getClass().getName());
        System.out.println("是否为代理：" + Proxy.isProxyClass(proxy.getClass()));
        
        // 调用代理方法
        System.out.println("\n调用代理方法：");
        String result1 = proxy.findUser("user123");
        System.out.println("findUser结果：" + result1);
        
        boolean result2 = proxy.saveUser("newUser", "password");
        System.out.println("saveUser结果：" + result2);
        
        try {
            proxy.deleteUser("admin");
        } catch (Exception e) {
            System.out.println("deleteUser异常：" + e.getMessage());
        }
    }
    
    /**
     * 演示代理模式应用
     */
    private static void demonstrateProxyApplications() {
        System.out.println("代理模式的应用场景：");
        System.out.println("1. AOP（面向切面编程）");
        System.out.println("2. 事务管理");
        System.out.println("3. 安全控制");
        System.out.println("4. 缓存代理");
        System.out.println("5. 远程代理");
        System.out.println("6. 延迟加载");
        System.out.println("7. 日志记录");
        System.out.println("8. 性能监控");
        
        // 缓存代理示例
        System.out.println("\n缓存代理示例：");
        DataService dataService = new DataServiceImpl();
        DataService cachedProxy = (DataService) Proxy.newProxyInstance(
            dataService.getClass().getClassLoader(),
            dataService.getClass().getInterfaces(),
            new CachingInvocationHandler(dataService)
        );
        
        // 第一次调用
        System.out.println("第一次调用：" + cachedProxy.getData("key1"));
        // 第二次调用（从缓存获取）
        System.out.println("第二次调用：" + cachedProxy.getData("key1"));
        // 不同key的调用
        System.out.println("不同key调用：" + cachedProxy.getData("key2"));
    }
    
    /**
     * 演示反射性能
     */
    private static void demonstrateReflectionPerformance() throws Exception {
        System.out.println("\n=== 反射性能演示 ===");
        
        System.out.println("反射性能：对比直接调用和反射调用的性能差异");
        
        Student student = new Student("性能测试", 20, "计算机");
        Class<Student> clazz = Student.class;
        Method getNameMethod = clazz.getMethod("getName");
        
        int iterations = 1000000;
        
        // 1. 直接调用性能测试
        System.out.println("\n1. 直接调用性能测试：");
        long startTime = System.nanoTime();
        for (int i = 0; i < iterations; i++) {
            String name = student.getName();
        }
        long directTime = System.nanoTime() - startTime;
        System.out.println("直接调用 " + iterations + " 次耗时：" + directTime / 1000000 + "ms");
        
        // 2. 反射调用性能测试
        System.out.println("\n2. 反射调用性能测试：");
        startTime = System.nanoTime();
        for (int i = 0; i < iterations; i++) {
            Object name = getNameMethod.invoke(student);
        }
        long reflectionTime = System.nanoTime() - startTime;
        System.out.println("反射调用 " + iterations + " 次耗时：" + reflectionTime / 1000000 + "ms");
        
        // 3. 缓存Method对象的反射调用
        System.out.println("\n3. 缓存Method对象的反射调用：");
        getNameMethod.setAccessible(true); // 跳过安全检查
        startTime = System.nanoTime();
        for (int i = 0; i < iterations; i++) {
            Object name = getNameMethod.invoke(student);
        }
        long cachedReflectionTime = System.nanoTime() - startTime;
        System.out.println("缓存反射调用 " + iterations + " 次耗时：" + cachedReflectionTime / 1000000 + "ms");
        
        // 4. 性能对比
        System.out.println("\n4. 性能对比：");
        System.out.println("直接调用：" + directTime / 1000000 + "ms");
        System.out.println("反射调用：" + reflectionTime / 1000000 + "ms (" + 
                          String.format("%.2f", (double) reflectionTime / directTime) + "倍)");
        System.out.println("缓存反射：" + cachedReflectionTime / 1000000 + "ms (" + 
                          String.format("%.2f", (double) cachedReflectionTime / directTime) + "倍)");
        
        // 5. 反射性能优化建议
        System.out.println("\n5. 反射性能优化建议：");
        demonstrateReflectionOptimization();
    }
    
    /**
     * 演示反射性能优化
     */
    private static void demonstrateReflectionOptimization() {
        System.out.println("反射性能优化策略：");
        System.out.println("1. 缓存Class、Method、Field对象");
        System.out.println("2. 使用setAccessible(true)跳过安全检查");
        System.out.println("3. 避免在循环中进行反射操作");
        System.out.println("4. 使用MethodHandle（JDK 7+）");
        System.out.println("5. 考虑使用字节码生成技术");
        System.out.println("6. 合理使用反射，避免过度使用");
        
        // 缓存示例
        System.out.println("\n缓存示例：");
        ReflectionCache cache = ReflectionCache.getInstance();
        
        try {
            Method method1 = cache.getMethod(Student.class, "getName");
            Method method2 = cache.getMethod(Student.class, "getName");
            System.out.println("缓存有效：" + (method1 == method2));
            
            Field field1 = cache.getField(Student.class, "name");
            Field field2 = cache.getField(Student.class, "name");
            System.out.println("字段缓存有效：" + (field1 == field2));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 演示反射应用场景
     */
    private static void demonstrateReflectionApplications() {
        System.out.println("\n=== 反射应用场景演示 ===");
        
        System.out.println("反射的实际应用场景：");
        
        // 1. 对象序列化
        System.out.println("\n1. 对象序列化：");
        demonstrateObjectSerialization();
        
        // 2. 依赖注入
        System.out.println("\n2. 依赖注入：");
        demonstrateDependencyInjection();
        
        // 3. ORM映射
        System.out.println("\n3. ORM映射：");
        demonstrateORMMapping();
        
        // 4. 单元测试
        System.out.println("\n4. 单元测试：");
        demonstrateUnitTesting();
        
        System.out.println("\n反射应用总结：");
        System.out.println("1. 框架开发：Spring、Hibernate、MyBatis等");
        System.out.println("2. 工具开发：IDE、调试器、分析工具等");
        System.out.println("3. 中间件：序列化、RPC、消息队列等");
        System.out.println("4. 测试工具：JUnit、Mockito等");
        System.out.println("5. 配置管理：注解处理、配置绑定等");
    }
    
    /**
     * 演示对象序列化
     */
    private static void demonstrateObjectSerialization() {
        System.out.println("使用反射实现简单的JSON序列化：");
        
        Student student = new Student("JSON测试", 22, "软件工程");
        String json = SimpleJsonSerializer.serialize(student);
        System.out.println("序列化结果：" + json);
    }
    
    /**
     * 演示依赖注入
     */
    private static void demonstrateDependencyInjection() {
        System.out.println("使用反射实现简单的依赖注入：");
        
        try {
            SimpleContainer container = new SimpleContainer();
            container.register(UserService.class, UserServiceImpl.class);
            
            UserController controller = container.getInstance(UserController.class);
            controller.handleRequest();
        } catch (Exception e) {
            System.err.println("依赖注入失败：" + e.getMessage());
        }
    }
    
    /**
     * 演示ORM映射
     */
    private static void demonstrateORMMapping() {
        System.out.println("使用反射实现简单的ORM映射：");
        
        // 模拟数据库记录
        Map<String, Object> record = new HashMap<>();
        record.put("student_name", "ORM测试");
        record.put("student_age", 21);
        record.put("major", "数据库");
        
        Student student = SimpleORM.mapToObject(record, Student.class);
        System.out.println("ORM映射结果：" + student);
    }
    
    /**
     * 演示单元测试
     */
    private static void demonstrateUnitTesting() {
        System.out.println("使用反射实现简单的单元测试框架：");
        
        SimpleTestRunner runner = new SimpleTestRunner();
        runner.runTests(TestClass.class);
    }
}

// ==================== 测试类和接口 ====================

/**
 * 学生实体类
 * 用于演示反射的各种操作
 */
@Entity(tableName = "students", description = "学生表")
class Student {
    
    // 静态字段
    private static int count = 0;
    
    // 实例字段
    @Column(name = "student_name", nullable = false, length = 50)
    public String name;
    
    @Column(name = "student_age", nullable = false)
    private int age;
    
    @Column(name = "major", nullable = true, length = 100)
    private final String major;
    
    @Deprecated
    private String oldField = "deprecated";
    
    // 泛型字段
    private List<String> courses = new ArrayList<>();
    private Map<String, Double> scores = new HashMap<>();
    
    // 构造器
    public Student() {
        this.major = "未定义";
        count++;
    }
    
    public Student(String name, int age, String major) {
        this.name = name;
        this.age = age;
        this.major = major;
        count++;
    }
    
    private Student(String name) {
        this.name = name;
        this.age = 0;
        this.major = "私有构造";
        count++;
    }
    
    // 公共方法
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    public String getMajor() {
        return major;
    }
    
    @Transactional(value = "REQUIRED", readOnly = false)
    public String study(String subject) {
        return name + " 正在学习 " + subject;
    }
    
    // 私有方法
    private double calculateGPA(double[] scores) {
        if (scores == null || scores.length == 0) {
            return 0.0;
        }
        
        double sum = 0;
        for (double score : scores) {
            sum += score;
        }
        return sum / scores.length;
    }
    
    // 静态方法
    private static int getNextId() {
        return ++count;
    }
    
    public static int getCount() {
        return count;
    }
    
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", major='" + major + '\'' +
                '}';
    }
}

/**
 * 泛型类示例
 */
class GenericClass<T extends Number, U> {
    private List<T> list;
    private Map<String, U> map;
    private T[] array;
    
    public <V extends Comparable<V>> V process(V input) {
        return input;
    }
    
    public List<T> getList() {
        return list;
    }
    
    public Map<String, U> getMap() {
        return map;
    }
}

/**
 * 继承泛型类的具体类
 */
class StringList extends ArrayList<String> implements Comparable<StringList> {
    @Override
    public int compareTo(StringList other) {
        return Integer.compare(this.size(), other.size());
    }
}

// ==================== 注解定义 ====================

/**
 * 实体注解
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Entity {
    String tableName();
    String description() default "";
}

/**
 * 列注解
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Column {
    String name();
    boolean nullable() default true;
    int length() default 255;
}

/**
 * 事务注解
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Transactional {
    String value() default "REQUIRED";
    boolean readOnly() default false;
}

/**
 * 测试注解
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Test {
    String description() default "";
}

/**
 * 注入注解
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Inject {
}

// ==================== 服务接口和实现 ====================

/**
 * 用户服务接口
 */
interface UserService {
    String findUser(String id);
    boolean saveUser(String username, String password);
    void deleteUser(String id) throws Exception;
}

/**
 * 用户服务实现
 */
class UserServiceImpl implements UserService {
    @Override
    public String findUser(String id) {
        return "User: " + id;
    }
    
    @Override
    public boolean saveUser(String username, String password) {
        System.out.println("保存用户：" + username);
        return true;
    }
    
    @Override
    public void deleteUser(String id) throws Exception {
        if ("admin".equals(id)) {
            throw new Exception("不能删除管理员");
        }
        System.out.println("删除用户：" + id);
    }
}

/**
 * 数据服务接口
 */
interface DataService {
    String getData(String key);
}

/**
 * 数据服务实现
 */
class DataServiceImpl implements DataService {
    @Override
    public String getData(String key) {
        // 模拟耗时操作
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return "Data for " + key + " at " + System.currentTimeMillis();
    }
}

/**
 * 用户控制器
 */
class UserController {
    @Inject
    private UserService userService;
    
    public void handleRequest() {
        if (userService != null) {
            System.out.println("处理请求：" + userService.findUser("123"));
        } else {
            System.out.println("UserService未注入");
        }
    }
}

// ==================== 动态代理处理器 ====================

/**
 * 服务调用处理器
 */
class ServiceInvocationHandler implements InvocationHandler {
    private final Object target;
    
    public ServiceInvocationHandler(Object target) {
        this.target = target;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("[代理] 调用方法：" + method.getName());
        System.out.println("[代理] 参数：" + Arrays.toString(args));
        
        long startTime = System.currentTimeMillis();
        
        try {
            Object result = method.invoke(target, args);
            long endTime = System.currentTimeMillis();
            System.out.println("[代理] 方法执行成功，耗时：" + (endTime - startTime) + "ms");
            return result;
        } catch (InvocationTargetException e) {
            long endTime = System.currentTimeMillis();
            System.out.println("[代理] 方法执行失败，耗时：" + (endTime - startTime) + "ms");
            throw e.getTargetException();
        }
    }
}

/**
 * 缓存调用处理器
 */
class CachingInvocationHandler implements InvocationHandler {
    private final Object target;
    private final Map<String, Object> cache = new ConcurrentHashMap<>();
    
    public CachingInvocationHandler(Object target) {
        this.target = target;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String cacheKey = method.getName() + Arrays.toString(args);
        
        if (cache.containsKey(cacheKey)) {
            System.out.println("[缓存] 命中缓存：" + cacheKey);
            return cache.get(cacheKey);
        }
        
        System.out.println("[缓存] 执行方法：" + cacheKey);
        Object result = method.invoke(target, args);
        cache.put(cacheKey, result);
        return result;
    }
}

// ==================== 工具类 ====================

/**
 * 反射缓存工具类
 */
class ReflectionCache {
    private static final ReflectionCache INSTANCE = new ReflectionCache();
    
    private final Map<String, Method> methodCache = new ConcurrentHashMap<>();
    private final Map<String, Field> fieldCache = new ConcurrentHashMap<>();
    private final Map<String, Constructor<?>> constructorCache = new ConcurrentHashMap<>();
    
    private ReflectionCache() {}
    
    public static ReflectionCache getInstance() {
        return INSTANCE;
    }
    
    /**
     * 获取缓存的方法
     */
    public Method getMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) throws NoSuchMethodException {
        String key = clazz.getName() + "." + methodName + Arrays.toString(paramTypes);
        return methodCache.computeIfAbsent(key, k -> {
            try {
                return clazz.getDeclaredMethod(methodName, paramTypes);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        });
    }
    
    /**
     * 获取缓存的字段
     */
    public Field getField(Class<?> clazz, String fieldName) throws NoSuchFieldException {
        String key = clazz.getName() + "." + fieldName;
        return fieldCache.computeIfAbsent(key, k -> {
            try {
                return clazz.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                throw new RuntimeException(e);
            }
        });
    }
    
    /**
     * 获取缓存的构造器
     */
    public Constructor<?> getConstructor(Class<?> clazz, Class<?>... paramTypes) throws NoSuchMethodException {
        String key = clazz.getName() + ".constructor" + Arrays.toString(paramTypes);
        return constructorCache.computeIfAbsent(key, k -> {
            try {
                return clazz.getDeclaredConstructor(paramTypes);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        });
    }
    
    /**
     * 清空缓存
     */
    public void clearCache() {
        methodCache.clear();
        fieldCache.clear();
        constructorCache.clear();
    }
}

/**
 * 简单JSON序列化器
 */
class SimpleJsonSerializer {
    
    /**
     * 将对象序列化为JSON字符串
     */
    public static String serialize(Object obj) {
        if (obj == null) {
            return "null";
        }
        
        Class<?> clazz = obj.getClass();
        StringBuilder json = new StringBuilder();
        json.append("{");
        
        Field[] fields = clazz.getDeclaredFields();
        boolean first = true;
        
        for (Field field : fields) {
            // 跳过静态字段
            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            
            try {
                field.setAccessible(true);
                Object value = field.get(obj);
                
                if (!first) {
                    json.append(",");
                }
                first = false;
                
                json.append("\"").append(field.getName()).append("\":");
                
                if (value == null) {
                    json.append("null");
                } else if (value instanceof String) {
                    json.append("\"").append(value).append("\"");
                } else if (value instanceof Number || value instanceof Boolean) {
                    json.append(value);
                } else {
                    json.append("\"").append(value.toString()).append("\"");
                }
            } catch (IllegalAccessException e) {
                System.err.println("无法访问字段：" + field.getName());
            }
        }
        
        json.append("}");
        return json.toString();
    }
}

/**
 * 简单依赖注入容器
 */
class SimpleContainer {
    private final Map<Class<?>, Class<?>> bindings = new HashMap<>();
    private final Map<Class<?>, Object> instances = new HashMap<>();
    
    /**
     * 注册接口和实现的绑定关系
     */
    public <T> void register(Class<T> interfaceClass, Class<? extends T> implementationClass) {
        bindings.put(interfaceClass, implementationClass);
    }
    
    /**
     * 获取实例（支持依赖注入）
     */
    @SuppressWarnings("unchecked")
    public <T> T getInstance(Class<T> clazz) throws Exception {
        // 检查是否已有实例
        if (instances.containsKey(clazz)) {
            return (T) instances.get(clazz);
        }
        
        // 获取实现类
        Class<?> implementationClass = bindings.getOrDefault(clazz, clazz);
        
        // 创建实例
        Constructor<?> constructor = implementationClass.getDeclaredConstructor();
        Object instance = constructor.newInstance();
        
        // 注入依赖
        injectDependencies(instance);
        
        // 缓存实例
        instances.put(clazz, instance);
        
        return (T) instance;
    }
    
    /**
     * 注入依赖
     */
    private void injectDependencies(Object instance) throws Exception {
        Class<?> clazz = instance.getClass();
        Field[] fields = clazz.getDeclaredFields();
        
        for (Field field : fields) {
            if (field.isAnnotationPresent(Inject.class)) {
                field.setAccessible(true);
                Class<?> fieldType = field.getType();
                Object dependency = getInstance(fieldType);
                field.set(instance, dependency);
            }
        }
    }
}

/**
 * 简单ORM映射工具
 */
class SimpleORM {
    
    /**
     * 将Map数据映射到对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T mapToObject(Map<String, Object> data, Class<T> clazz) {
        try {
            // 创建对象实例
            Constructor<T> constructor = clazz.getDeclaredConstructor();
            T instance = constructor.newInstance();
            
            // 映射字段
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(Column.class)) {
                    Column column = field.getAnnotation(Column.class);
                    String columnName = column.name();
                    
                    if (data.containsKey(columnName)) {
                        field.setAccessible(true);
                        Object value = data.get(columnName);
                        
                        // 类型转换
                        if (value != null && !field.getType().isAssignableFrom(value.getClass())) {
                            value = convertType(value, field.getType());
                        }
                        
                        field.set(instance, value);
                    }
                }
            }
            
            return instance;
        } catch (Exception e) {
            throw new RuntimeException("ORM映射失败", e);
        }
    }
    
    /**
     * 类型转换
     */
    private static Object convertType(Object value, Class<?> targetType) {
        if (targetType == String.class) {
            return value.toString();
        } else if (targetType == int.class || targetType == Integer.class) {
            return Integer.valueOf(value.toString());
        } else if (targetType == long.class || targetType == Long.class) {
            return Long.valueOf(value.toString());
        } else if (targetType == double.class || targetType == Double.class) {
            return Double.valueOf(value.toString());
        } else if (targetType == boolean.class || targetType == Boolean.class) {
            return Boolean.valueOf(value.toString());
        }
        return value;
    }
}

/**
 * 简单测试运行器
 */
class SimpleTestRunner {
    
    /**
     * 运行测试类中的所有测试方法
     */
    public void runTests(Class<?> testClass) {
        System.out.println("运行测试类：" + testClass.getName());
        
        Method[] methods = testClass.getDeclaredMethods();
        int totalTests = 0;
        int passedTests = 0;
        
        for (Method method : methods) {
            if (method.isAnnotationPresent(Test.class)) {
                totalTests++;
                
                Test testAnnotation = method.getAnnotation(Test.class);
                String description = testAnnotation.description();
                if (description.isEmpty()) {
                    description = method.getName();
                }
                
                System.out.print("运行测试：" + description + " ... ");
                
                try {
                    // 创建测试实例
                    Object testInstance = testClass.getDeclaredConstructor().newInstance();
                    
                    // 调用测试方法
                    method.setAccessible(true);
                    method.invoke(testInstance);
                    
                    System.out.println("通过");
                    passedTests++;
                } catch (Exception e) {
                    System.out.println("失败：" + e.getCause().getMessage());
                }
            }
        }
        
        System.out.println("\n测试结果：" + passedTests + "/" + totalTests + " 通过");
    }
}

/**
 * 测试类
 */
class TestClass {
    
    @Test(description = "测试字符串相等")
    public void testStringEquals() {
        String str1 = "Hello";
        String str2 = "Hello";
        if (!str1.equals(str2)) {
            throw new AssertionError("字符串应该相等");
        }
    }
    
    @Test(description = "测试数字计算")
    public void testMath() {
        int result = 2 + 3;
        if (result != 5) {
            throw new AssertionError("2 + 3 应该等于 5");
        }
    }
    
    @Test(description = "测试失败情况")
    public void testFailure() {
        throw new AssertionError("这是一个故意失败的测试");
    }
    
    // 非测试方法
    public void normalMethod() {
        System.out.println("这不是测试方法");
    }
}